#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.


import logging
import os

from flask import Flask, send_from_directory

from config.config import get_config
from extensions.exception import init_exception
from common_libs.sqlitedb import FCE_DB
from common_libs.db_correct import init_correct_sqlite
from routes.routes import init_routers

def create_serv():
    serv = Flask(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
    serv_config = get_config()
    serv.config['IS_DEBUG'] = serv_config['is_debug']
    serv.config["FCEUtil_BIN"] = serv_config['fce_util']
    serv.config['obj'] = serv_config

    # jwt 配置
    serv.config['SECRET_KEY'] = serv_config['jwt_secret_key']
    serv.config["JWT_TOKEN_EXPIRES"] = serv_config['jwt_expire_time']
    serv.config["JWT_TOKEN_RELEASE"] = serv_config['jwt_release_time']

    # init logger
    handler = logging.handlers.RotatingFileHandler(serv_config['access_log_file'], maxBytes=1024 * 1024, backupCount=30)
    formatter = logging.Formatter(serv_config['access_log_format'])
    logging.basicConfig(level=logging.DEBUG)
    handler.setFormatter(formatter)
    serv.logger.addHandler(handler)
    serv.logger=logging.LoggerAdapter(serv.logger, {'cluster':'fce'})
    
    # init operate logger
    handler = logging.handlers.RotatingFileHandler(serv_config['operate_log_file'], maxBytes=1024 * 1024, backupCount=30)
    formatter = logging.Formatter(serv_config['operate_log_format'])
    handler.setFormatter(formatter)
    optLogger = logging.getLogger('operate_logger')
    optLogger.addHandler(handler)

    @serv.after_request
    def add_cors_headers(response):
        response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有来源的跨域请求
        response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, ClientAccount, ClientLanguage'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS, PATCH'  # 允许的请求方法
        return response

    # 注册路由
    init_routers(serv)
    serv.logger.info("initialize routers ok")

    # 注册扩展
    init_exception(serv)

    # 矫正sqlite
    pwd = os.path.dirname(os.path.abspath(__file__))
    sqlite_db_path = os.path.join(pwd, 'sqlite.db')
    init_correct_sqlite(sqlite_db_path)
    serv.logger.info("init_correct_sqlite ok")

    serv.config["optLogger"] = optLogger
    serv.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////%s' % sqlite_db_path
    serv.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

    FCE_DB.init_app(serv)
    with serv.app_context():
        FCE_DB.create_all()

    serv.logger.info("server init success")
    return serv
